package org.dromara.tearoom.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.tearoom.config.MeiTuanConfig;
import org.dromara.tearoom.domain.TerGroupBuy;
import org.dromara.tearoom.domain.bo.TerGroupBuyBo;
import org.dromara.tearoom.domain.enums.CouponPlateTypeEnum;
import org.dromara.tearoom.domain.enums.GroupBuyRelateTypeEnum;
import org.dromara.tearoom.domain.enums.GroupBuyStateEnum;
import org.dromara.tearoom.domain.vo.TerCouponTemplateVo;
import org.dromara.tearoom.domain.vo.TerGroupBuyVo;
import org.dromara.tearoom.service.ITerCouponService;
import org.dromara.tearoom.service.ITerCouponTemplateService;
import org.dromara.tearoom.service.ITerGroupBuyService;
import org.dromara.tearoom.service.IThirdGroupBuyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 美团服务
 * @author CKJ
 * @description: 美团服务
 * @date 2025/4/10 17:39
 */
@Slf4j
@Service("MT")
@RequiredArgsConstructor
public class MeiTuanServiceImpl implements IThirdGroupBuyService {


    private final MeiTuanConfig meiTuanConfig;
    private final ITerGroupBuyService terGroupBuyService;
    private final ITerCouponService terCouponService;
    private final ITerCouponTemplateService terCouponTemplateService;


    /**
     * 验卷准备
     *
     * @param shortUrl
     * @return
     */
    @Override
    public List<TerGroupBuyVo> certificatePrepare(String shortUrl, String code, String storeId) {
        TerGroupBuyBo query=new TerGroupBuyBo();
        HttpRequest request = HttpUtil.createPost(meiTuanConfig.getBaseUrl()+"/admin-api/iot/groupPay/prepare");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("clientId", meiTuanConfig.getAppId());
        headers.put("secret", meiTuanConfig.getAppSecret());
        request.addHeaders(headers);
        JSONObject body = new JSONObject();
        body.putOpt("groupPayType",1);
        if(StrUtil.isBlank(storeId)){
            body.putOpt("storeId", meiTuanConfig.getStoreId());
        }else{
            body.putOpt("storeId", storeId);
        }
        if(StrUtil.isNotBlank(shortUrl)){
            String decode=Base64.decodeStr(shortUrl);
            log.info("短链：{}",shortUrl);
            log.info("解码短链：{}", decode);
            body.putOpt("ticketNo", decode);
            query.setCode(decode);
        }
        if(StrUtil.isNotBlank(code)){
            body.putOpt("ticketNo", code);
            query.setCode(code);
        }
        String str = request.body(body.toString()).timeout(1000).execute().body();
        log.info(str);
        List<TerGroupBuyBo> addList=new ArrayList<>();
        JSONObject json = JSONUtil.parseObj(str);
        if(json.getInt("code")!=0){
            log.error("二维码:{},劵码:{},错误:{}",shortUrl,code,json.getStr("msg"));
            throw new ServiceException(json.getStr("msg"));
        }
        JSONObject data= JSONUtil.parseObj(json.getStr("data"));
        TerCouponTemplateVo couponTemplateVo = terCouponTemplateService.queryByThirdPlateId(data.getStr("shopId"));
        JSONObject ticketData= JSONUtil.parseObj(data.getStr("ticketData"));
        List<JSONObject> paymentDetailList= JSONUtil.toList(ticketData.getStr("paymentDetail"),JSONObject.class);
        JSONObject paymentDetail = paymentDetailList.stream()
                .filter(item -> !item.isNull("amountType") && 10 == item.getInt("amountType"))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("未找到amountType=10的支付明细"));
        TerGroupBuyBo bo = new TerGroupBuyBo();
        bo.setUserId(LoginHelper.getAppLoginUser().getId());
        bo.setName(data.getStr("ticketName"));
        bo.setRelateId(couponTemplateVo.getId());
        bo.setRelateType(GroupBuyRelateTypeEnum.COUPON.getType());
        bo.setStatus(GroupBuyStateEnum.UN_USED.getState());
        bo.setOriginalAmount(data.getInt("payAmount"));
        bo.setPayAmount(paymentDetail.getBigDecimal("amount").multiply(new BigDecimal(100)).intValue());
        bo.setStartTime(new Date());
        bo.setExpireTime(DateUtil.date(ticketData.getLong("receiptEndDate")));
        bo.setPlateType(CouponPlateTypeEnum.MT.getType());
        bo.setType(ticketData.getInt("dealType"));
        bo.setCreateTime(new Date());
        bo.setCode(query.getCode());
        bo.setEncryptedCode(data.getStr("ticketInfo"));
        addList.add(bo);
        terGroupBuyService.insertBatchByBo(addList);
        return terGroupBuyService.queryList(query);
    }

    /**
     * 核销验卷
     *
     * @param encryptedCodes
     * @param storeId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void certificate(String encryptedCodes, String storeId,Long groupBuyId) {
        TerGroupBuy groupBuy=terGroupBuyService.queryEntityById(groupBuyId);
        if(ObjectUtil.isEmpty(groupBuy)){
            throw new ServiceException("优惠券不存在！");
        }
        if(GroupBuyStateEnum.isUsed(groupBuy.getStatus())){
            throw new ServiceException("优惠券已核销！");
        }
        HttpRequest request = HttpUtil.createPost(meiTuanConfig.getBaseUrl()+"/admin-api/iot/groupPay/consumeNew");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("clientId", meiTuanConfig.getAppId());
        headers.put("secret", meiTuanConfig.getAppSecret());
        request.addHeaders(headers);
        log.info(headers.toString());
        JSONObject body = new JSONObject();
        body.putOpt("groupPayType",1);
        if(StrUtil.isBlank(storeId)){
            body.putOpt("storeId", meiTuanConfig.getStoreId());
        }else{
            body.putOpt("storeId", storeId);
        }
        body.putOpt("ticketNo", groupBuy.getCode());
        body.putOpt("ticketInfo", groupBuy.getEncryptedCode());
        log.info(body.toString());
        String str = request.body(body.toString()).timeout(2000).execute().body();
        log.info(str);
        JSONObject json = JSONUtil.parseObj(str);
        if(json.getInt("code")!=0){
            log.error(json.getStr("msg"));
            throw new ServiceException(json.getStr("msg"));
        }
        //JSONObject data= JSONUtil.parseObj(json.getStr("data"));
        groupBuy.setStatus(GroupBuyStateEnum.USED.getState());
        groupBuy.setUseTime(new Date());
        terGroupBuyService.updateById(groupBuy);
        Set<Long> userIds=new HashSet<>();
        userIds.add(groupBuy.getUserId());
        terCouponService.takeCouponByGroupBy(groupBuy.getRelateId(),groupBuy.getId(),userIds,"美团核销");
    }


}
